<template lang="html">
  <div id="infoConfirm-wrap">
    <!-- 订单 -->
    <section class="infoConfirm-indent">
      <house-list v-if="houseData" :houseInfo="houseData" detailPath="/infoConfirm"></house-list>
    </section>

    <!-- 签约人信息 -->
    <section>
      <div class="title">
        <p class="left">签约人信息</p>
      </div>
      <user-info :user="currentUser" disabled></user-info>
    </section>

    <!-- 新增租客信息 -->
    <section v-for="(item, index) in newTenantArray" :key="index">
      <div class="title">
        <p class="left">入住人<span class="num">（{{index + 1}}）</span>信息</p>
        <p class="remove" @click="removeTenant(index)">删除</p>
      </div>
      <user-info :user="newTenantArray[index]" v-model="newTenantArray[index]"></user-info>
    </section>

    <!-- 新增按钮 -->
    <div class="add-btn">
      <p @click="newTenantArray.push({})"><i class="plus"></i> 新增</p>
    </div>

    <div class="infoConfirm-submit">
      <x-button type="primary" @click.native="submit">提交</x-button>
    </div>

    <x-dialog v-model="hintDialog" class="dialog-hint">
      <p class="hint-black">请确保您与房东已达成签约意向再来线上签约，为了保护您的利益，了解以下几点。</p>
      <ol class="hint-content">
        <li>1.在未完成交易的情况下，请不要和房东交换联系方式，包括主动提供和索要手机号码、QQ或微信等。预约成功后，平台将房东的联系方式发送给你</li>
        <li>2.平台信息均真实有效，并会提供一系列的保障来证明您的权益；</li>
        <li>3.请勿通过微信支付或支付宝等方式直接将任何款项打给房东，以防诈骗，造成您的钱款损失。</li>
      </ol>
      <x-button type="primary" @click.native="hintDialog = false">我已知道</x-button>
      <i class="icon icon-close" @click="hintDialog = false"></i>
    </x-dialog>
  </div>
</template>

<script>
import { XDialog, Flow, FlowState, FlowLine, XButton, Calendar } from 'vux'
import houseList from '@/components/houseList'
import UserInfo from './child/UserInfo.vue'
export default {
  components: {
    Flow,
    FlowState,
    FlowLine,
    XButton,
    houseList,
    Calendar,
    XDialog,
    UserInfo
  },
  data () {
    return {
      newTenantArray: [], // 入住人信息
      currentUser: {}, // 签约人信息
      houseData: {},
      // dates: dates,
      show: false, // 显示弹窗
      hintDialog: true,
      beginTime: '', // 起租时间
      endTime: '' // 截止时间
    }
  },
  methods: {
    removeTenant (index) {
      // 删除入住人
      const _this = this
      this.$vux.confirm.show({
        title: '确定删除该租客?',
        onConfirm () {
          _this.newTenantArray.splice(index, 1)
          _this.updateSession()
        }
      })
    },
    // 数据校验
    checkData (data) {
      let idCardTemp = []
      let len = data.length
      for (let i = 0; i < len; i++) {
        let tenant = data[i]
        if (tenant.trueName === '') {
          this.$vux.toast.text(`请输入第${i + 1}位租客的姓名`)
          return false
        } else if (!/^[A-Za-z\u4e00-\u9fa5]+$/.test(tenant.trueName)) {
          this.$vux.toast.text(`第${i + 1}位租客的姓名格式有误`)
          return false
        } else if (tenant.sex === '') {
          this.$vux.toast.text(`请选择第${i + 1}位租客的性别`)
          return false
        } else if (tenant.idCard === '') {
          this.$vux.toast.text(`请输入第${i + 1}位租客的身份证号码`)
          return false
        } else if (idCardTemp.indexOf(tenant.idCard) > -1) {
          this.$vux.toast.text(`第${i + 1}位租客的身份证号码已存在`)
          return false
        } else if (!/^(\d{17}[\d|x]|\d{15})$/gi.test(tenant.idCard)) {
          this.$vux.toast.text(`第${i + 1}位租客的身份证号码格式错误`)
          return false
        } else if (tenant.mobile === '') {
          this.$vux.toast.text(`请输入第${i + 1}位租客的手机号码`)
          return false
        } else if (!/^1[3|4|5|7|8]\d{9}$/gi.test(tenant.mobile)) {
          this.$vux.toast.text(`第${i + 1}位租客的手机号码格式错误`)
          return false
        }
        idCardTemp.push(tenant.idCard)
      }
      return true
    },
    updateSession () {
      let currentUser = JSON.parse(window.localStorage.getItem('userInfo'))
      let sex = '1'
      switch (currentUser.sex) {
        case '男':
          console.log('男')
          sex = '1'
          break
        case '女':
          sex = '0'
          break
      }
      let signUser = {
        trueName: currentUser.trueName || '',
        sex: sex,
        idCard: currentUser.idCard || '',
        mobile: currentUser.mobile || ''
      }
      let tenantsInfo = this.newTenantArray.concat()
      tenantsInfo.unshift(signUser)
      window.localStorage.setItem('tenantsInfo', JSON.stringify(tenantsInfo))
    },
    // 提交授权
    submit () {
      if (this.checkData(this.newTenantArray)) {
        this.updateSession()
        this.$router.push('/orgSignInfo')
      }
    }
  },
  created () {
    let houseInfo = JSON.parse(window.localStorage.getItem('signHouseInfo')) // 房源信息
    this.houseData = {
      id: houseInfo.id || '',
      landlordId: houseInfo.partyAId || '',
      houseTitle: `${houseInfo.buildingName} ${houseInfo.roomName}` || '',
      coverImg: houseInfo.apartment.cover || '',
      address: houseInfo.apartment.address || '',
      rentalPrice: houseInfo.rent || '',
      betPrice: houseInfo.rent || '',
      highlights: houseInfo.highlights || '',
      createTime: houseInfo.apartment.createTime || '',
      area: houseInfo.area || ''
    }

    let newTenantArray = JSON.parse(window.localStorage.getItem('tenantsInfo') || '[]') // 入住人信息
    newTenantArray.length > 0 ? newTenantArray.shift() : []
    this.newTenantArray = newTenantArray

    let currentUser = JSON.parse(window.localStorage.getItem('userInfo') || '{}')
    try {
      this.currentUser = {
        trueName: currentUser.trueName || '',
        mobile: currentUser.mobile.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
      }
      this.currentUser.sex = parseInt(currentUser.idCard[16]) & 1 ? '男' : '女' // 身份证倒数第二位 奇数 男， 偶数 女
      this.currentUser.idCard = currentUser.idCard.replace(/(\d{4})\d*(\d{4})/, '$1**********$2') || ''
    } catch (e) {
      this.$vux.toast.text('无法获取用户信息')
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.name !== 'signInfo') {
      window.localStorage.setItem('tenantsInfo', '[]')
    }
    next()
  }
}
</script>

<style lang="less" scoped>
  @import "../../styles/baseVar.less";
  ul, li{
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .pad-side-10{
    padding: 0 10px; /* 20/40 */
  }
  #infoConfirm-wrap{
    min-height: 100vh;
    background: #f4f4f4;
    section{
      background: #fff;
      margin-bottom: 6px;
      .title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;
        padding: 15px 0;
        box-sizing: border-box;
        .left{
          padding-left: 12px;
          border-left: 3px solid #ff9600;
          line-height: 1.25;
        }
        .remove{
          font-size: 12px;
          padding-right: 15px;
          color: #2872e2;
        }
      }
    }
    .add-btn{
      padding: 14px 0;
      text-align: center;
      line-height: 30px;
      background: #fff;
      p{
        display: inline-block;
        width: 80px;
        height: 30px;
        font-size: 12px;
        color: #585858;
        border: 1px solid #bbb;
        border-radius: 3px;
        box-sizing: border-box;
      }
      .plus{
        display: inline-block;
        position: relative;
        width: 9px;
        height: 9px;
        &::before, &::after{
          display: block;
          content: "";
          position: absolute;
          background: #333;
          width: 100%;
          height: 2px;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          margin: auto;
        }
        &:after{
          transform: rotate(90deg);
        }
      }
    }
  }
</style>

<style lang="less">
  @import "../../styles/baseVar.less";
  #infoConfirm-wrap{
    .dialog-hint{
      .weui-dialog{
        padding: 15px;
        box-sizing: border-box;
        color: #343434;
        text-align: left;
        overflow: initial;
        margin-top: -30px;
        .infoConfirm-hint{
          font-size: 22px;
          text-align: center;
        }
        .hint-black{
          font-size: 16px;
        }
        .hint-content{
          font-size: 12px;
          color: #777;
          li{
            margin-top: 20px;
            margin-bottom: 20px;
          }
        }
        .icon-close{
          display: block;
          width: 35px;
          height: 35px;
          position: absolute;
          bottom: -63px;
          left: 0;
          right: 0;
          margin: auto;
          background: url('../../images/icon_close.png') center no-repeat;
          background-size: 100%;
        }
      }
    }
  }

</style>
